{mongoose} = require '../db/mongodb'
collectionEntities = require '../db/CollectionEntities'
fse = require 'fs-extra'
demoData =require '../demoData/demo2.json'
_ = require 'underscore'


collectionBuilder=
  createCollectionMap: (doc) ->
    collection=
     collection_type : "RemoteCollection"
     collection_name : "demo"
     app_id :doc.app_id
     attributes :[{
       "name": "title",
       "required": false,
       "type": "string"
     },{
       "name": "title02",
       "required": false,
       "type": "string"
     },{
       "name": "introduction",
       "required": false,
       "type": "string"
     },{
       "name": "content",
       "required": false,
       "type": "string"
     },{
       "name": "picture",
       "required": false,
       "type": "ImageArray"
     },{
       "name": "author",
       "required": false,
       "type": "string"
     },
      {
       "name": "time",
       "required": false,
       "type": "Date"
     }, {
       "name": "evaluation",
       "required": false,
       "type": "string"
     },{
       "name": "collections",
       "required": false,
       "type": "string"
     },{
       "name": "price",
       "required": false,
       "type": "string"
     },{
       "name": "press",
       "required": false,
       "type": "string"
     }]
    appModel = require '../db/AppModel'
    collectionEntities.save collection, (err,obj) ->
      return err if err
      #维护appjs的coolections
      appModel.findOne _id:obj.app_id , (err,appmodel) ->
        return err if err
        collections = appmodel.collections
        collections = {} unless collections
        collections[obj.collection_name] =
          "name" : obj.collection_name,
          "id" : obj.id,
          "type" : obj.collection_type,
          "url" : obj.collection_url
        appmodel.collections = collections
        appModel.update _id: appmodel.id, appmodel,(err,callback) ->
          return err if err

  createCollection:(obj,conn) ->
    schema = new mongoose.Schema {
        title: type: String , required: false
        title02: type: String , required: false
        introduction: type: String , required: false
        content: type: String , required: false
        picture: type: String , required: false
        author: type: String , required: false
        time: type: String , required: false
        evaluation: type: String , required: false
        collections: type: String , required: false
        price: type: String , required: false
        press: type: String , required: false
    }
    model = conn.model("demo", schema, "demo")
    _.each demoData, (item) ->
      new model(item).save (err, doc) ->
        return err if err



module.exports = collectionBuilder
